import * as vscode from 'vscode';
import { CompletionProvider } from './providers/completionProvider';
import { SidebarProvider } from './providers/sidebarProvider';
import { CodeGenerationService } from './services/codeGenerationService';
import { UnitTestService } from './services/unitTestService';
import { FuzzTestService } from './services/fuzzTestService';
import { GnModificationService } from './services/gnModificationService';
import { CodeAnalysisService } from './services/codeAnalysisService';
import { ApiClient } from './utils/apiClient';
import { AgentChatPanel } from './views/agentChatPanel';
import { startLspClient, stopLspClient } from './lsp/client';
import { ConfigurationManager } from './utils/configurationManager';

export function activate(context: vscode.ExtensionContext) {
    console.log('OH一点通插件已激活');

    // 初始化配置管理器
    const configManager = new ConfigurationManager();
    
    // 初始化API客户端
    const apiClient = new ApiClient(configManager);

    // 初始化服务
    const codeGenerationService = new CodeGenerationService(apiClient);
    const unitTestService = new UnitTestService(apiClient);
    const fuzzTestService = new FuzzTestService(apiClient);
    const gnModificationService = new GnModificationService(apiClient);
    const codeAnalysisService = new CodeAnalysisService(apiClient);

    // 注册侧边栏视图
    const sidebarProvider = new SidebarProvider();
    const sidebarView = vscode.window.registerTreeDataProvider(
        'oh-yidian-tong-main',
        sidebarProvider
    );
    context.subscriptions.push(sidebarView);
    
    // 调试：触发一次刷新确保数据加载
    setTimeout(() => {
        sidebarProvider.refresh();
    }, 100);

    // 如果未启用LSP，则注册本地补全提供者；启用LSP时由LSP提供补全
    const lspEnabled = vscode.workspace.getConfiguration('oh-yidian-tong').get<boolean>('lsp.enabled');
    let completionDisposable: vscode.Disposable | undefined;
    if (!lspEnabled) {
        const completionProvider = new CompletionProvider(apiClient);
        completionDisposable = vscode.languages.registerCompletionItemProvider(
            ['cpp', 'c', 'h'],
            completionProvider,
            '.', ':', '>', ' ', '\t'
        );
    }

    // 注册命令
    const commands = [
        vscode.commands.registerCommand('oh-yidian-tong.completeCode', async () => {
            await handleCodeCompletion(codeGenerationService);
        }),
        vscode.commands.registerCommand('oh-yidian-tong.generateCode', async () => {
            await handleCodeGeneration(codeGenerationService);
        }),
        vscode.commands.registerCommand('oh-yidian-tong.generateUnitTest', async () => {
            await handleUnitTestGeneration(unitTestService);
        }),
        vscode.commands.registerCommand('oh-yidian-tong.generateFuzzTest', async () => {
            await handleFuzzTestGeneration(fuzzTestService);
        }),
        vscode.commands.registerCommand('oh-yidian-tong.modifyGnFile', async () => {
            await handleGnModification(gnModificationService);
        }),
        vscode.commands.registerCommand('oh-yidian-tong.analyzeCode', async () => {
            await handleCodeAnalysis(codeAnalysisService);
        }),
        vscode.commands.registerCommand('oh-yidian-tong.configureSettings', async () => {
            await handleConfigureSettings();
        }),
        vscode.commands.registerCommand('oh-yidian-tong.openAgentChat', async () => {
            AgentChatPanel.createOrShow(context.extensionUri, apiClient);
        })
    ];

    // 注册所有disposables
    if (completionDisposable) {
        context.subscriptions.push(completionDisposable);
    }
    context.subscriptions.push(...commands);

    // 启动LSP客户端（可配置）
    startLspClient(context);

    // 显示欢迎消息
    vscode.window.showInformationMessage('OH一点通插件已激活！使用 Ctrl+Space 进行代码续写，Ctrl+Shift+G 进行代码生成');
}

async function handleCodeCompletion(service: CodeGenerationService) {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
        vscode.window.showWarningMessage('请先打开一个文件');
        return;
    }

    try {
        await vscode.window.withProgress({
            location: vscode.ProgressLocation.Notification,
            title: "OH一点通",
            cancellable: true
        }, async (progress, token) => {
            progress.report({ message: "正在生成代码续写建议..." });
            
            const result = await service.generateCodeCompletion(editor, token);
            
            if (result && result.length > 0) {
                // 显示补全建议
                const selected = await vscode.window.showQuickPick(
                    result.map(item => ({
                        label: item.label,
                        description: item.detail,
                        detail: item.documentation,
                        insertText: item.insertText
                    })),
                    { placeHolder: '选择代码续写建议' }
                );
                
                if (selected) {
                    const position = editor.selection.active;
                    await editor.edit(editBuilder => {
                        editBuilder.insert(position, selected.insertText);
                    });
                }
            } else {
                vscode.window.showInformationMessage('未找到合适的代码续写建议');
            }
        });
    } catch (error) {
        vscode.window.showErrorMessage(`代码续写失败: ${error}`);
    }
}

async function handleCodeGeneration(service: CodeGenerationService) {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
        vscode.window.showWarningMessage('请先打开一个文件');
        return;
    }

    const prompt = await vscode.window.showInputBox({
        prompt: '请输入代码生成提示',
        placeHolder: '例如：生成一个计算斐波那契数列的函数'
    });

    if (!prompt) {
        return;
    }

    try {
        await vscode.window.withProgress({
            location: vscode.ProgressLocation.Notification,
            title: "OH一点通",
            cancellable: true
        }, async (progress, token) => {
            progress.report({ message: "正在生成代码..." });
            
            const result = await service.generateCode(editor, prompt, token);
            
            if (result) {
                const position = editor.selection.active;
                await editor.edit(editBuilder => {
                    editBuilder.insert(position, result);
                });
                vscode.window.showInformationMessage('代码生成完成！');
            }
        });
    } catch (error) {
        vscode.window.showErrorMessage(`代码生成失败: ${error}`);
    }
}

async function handleUnitTestGeneration(service: UnitTestService) {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
        vscode.window.showWarningMessage('请先打开一个文件');
        return;
    }

    try {
        await vscode.window.withProgress({
            location: vscode.ProgressLocation.Notification,
            title: "OH一点通",
            cancellable: true
        }, async (progress, token) => {
            progress.report({ message: "正在生成单元测试..." });
            
            const result = await service.generateUnitTest(editor, token);
            
            if (result) {
                // 创建新文件显示生成的单元测试
                const doc = await vscode.workspace.openTextDocument({
                    content: result,
                    language: 'cpp'
                });
                await vscode.window.showTextDocument(doc);
                vscode.window.showInformationMessage('单元测试生成完成！');
            }
        });
    } catch (error) {
        vscode.window.showErrorMessage(`单元测试生成失败: ${error}`);
    }
}

async function handleFuzzTestGeneration(service: FuzzTestService) {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
        vscode.window.showWarningMessage('请先打开一个文件');
        return;
    }

    try {
        await vscode.window.withProgress({
            location: vscode.ProgressLocation.Notification,
            title: "OH一点通",
            cancellable: true
        }, async (progress, token) => {
            progress.report({ message: "正在生成Fuzz测试..." });
            
            const result = await service.generateFuzzTest(editor, token);
            
            if (result) {
                // 创建新文件显示生成的Fuzz测试
                const doc = await vscode.workspace.openTextDocument({
                    content: result,
                    language: 'cpp'
                });
                await vscode.window.showTextDocument(doc);
                vscode.window.showInformationMessage('Fuzz测试生成完成！');
            }
        });
    } catch (error) {
        vscode.window.showErrorMessage(`Fuzz测试生成失败: ${error}`);
    }
}

async function handleGnModification(service: GnModificationService) {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
        vscode.window.showWarningMessage('请先打开一个GN文件');
        return;
    }

    const action = await vscode.window.showQuickPick([
        { label: '添加源文件', description: '添加新的源文件到构建目标' },
        { label: '添加依赖', description: '添加新的依赖项' },
        { label: '修改编译选项', description: '修改编译参数' },
        { label: '添加测试目标', description: '添加单元测试目标' },
        { label: '添加Fuzz测试目标', description: '添加Fuzz测试目标' }
    ], { placeHolder: '选择要执行的GN操作' });

    if (!action) {
        return;
    }

    try {
        await vscode.window.withProgress({
            location: vscode.ProgressLocation.Notification,
            title: "OH一点通",
            cancellable: true
        }, async (progress, token) => {
            progress.report({ message: `正在${action.label}...` });
            
            const result = await service.modifyGnFile(editor, action.label, token);
            
            if (result) {
                await editor.edit(editBuilder => {
                    editBuilder.replace(new vscode.Range(0, 0, editor.document.lineCount, 0), result);
                });
                vscode.window.showInformationMessage(`${action.label}完成！`);
            }
        });
    } catch (error) {
        vscode.window.showErrorMessage(`${action.label}失败: ${error}`);
    }
}

async function handleCodeAnalysis(service: CodeAnalysisService) {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
        vscode.window.showWarningMessage('请先打开一个文件');
        return;
    }

    try {
        await vscode.window.withProgress({
            location: vscode.ProgressLocation.Notification,
            title: "OH一点通",
            cancellable: true
        }, async (progress, token) => {
            progress.report({ message: "正在分析代码..." });
            
            const result = await service.analyzeCode(editor, token);
            
            if (result) {
                // 显示分析结果
                const panel = vscode.window.createWebviewPanel(
                    'codeAnalysis',
                    '代码分析结果',
                    vscode.ViewColumn.Two,
                    {}
                );
                
                panel.webview.html = generateAnalysisHtml(result);
                vscode.window.showInformationMessage('代码分析完成！');
            }
        });
    } catch (error) {
        vscode.window.showErrorMessage(`代码分析失败: ${error}`);
    }
}

async function handleConfigureSettings() {
    await vscode.commands.executeCommand('workbench.action.openSettings', 'oh-yidian-tong');
}

function generateAnalysisHtml(analysisResult: any): string {
    return `
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>代码分析结果</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                .issue { margin: 10px 0; padding: 10px; border-left: 4px solid #ff6b6b; background: #f8f9fa; }
                .issue.error { border-color: #dc3545; }
                .issue.warning { border-color: #ffc107; }
                .issue.info { border-color: #17a2b8; }
                .score { font-size: 24px; font-weight: bold; color: #28a745; }
            </style>
        </head>
        <body>
            <h1>代码分析结果</h1>
            <div class="score">评分: ${analysisResult.score || 0}/100</div>
            <p><strong>摘要:</strong> ${analysisResult.summary || '无'}</p>
            
            <h2>问题列表</h2>
            ${(analysisResult.issues || []).map((issue: any) => `
                <div class="issue ${issue.severity}">
                    <h3>${issue.type} - ${issue.severity}</h3>
                    <p><strong>位置:</strong> ${issue.filePath}:${issue.startLine}-${issue.endLine}</p>
                    <p><strong>描述:</strong> ${issue.message}</p>
                    ${issue.fixSuggestion ? `<p><strong>修复建议:</strong> ${issue.fixSuggestion}</p>` : ''}
                </div>
            `).join('')}
        </body>
        </html>
    `;
}

export function deactivate() {
    console.log('OH一点通插件已停用');
    stopLspClient();
}
